package com.example.kafkalearn.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * 事务示例
 *
 * 开启事务的前提是必须开启幂等性（幂等性默认开启）
 * @author 何昌杰
 */
public class Producer7Start {
    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        // 重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG, 10);
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "10.51.34.61:9092");
        properties.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "transactionId");
        // 幂等性（幂等性默认开启）
        properties.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);

        KafkaProducer<String, String> producer = new KafkaProducer<>(properties);
        // 初始化事务
        producer.initTransactions();
        // 开始事务
        producer.beginTransaction();
        try {
            ProducerRecord record1 = new ProducerRecord<>("harris", "kafka-demo", "hello harris1!!!!");
            producer.send(record1);
            ProducerRecord record2 = new ProducerRecord<>("harris", "kafka-demo", "hello harris2!!!!");
            producer.send(record2);
            ProducerRecord record3 = new ProducerRecord<>("harris", "kafka-demo", "hello harris3!!!!");
            producer.send(record3);
            producer.commitTransaction();
        } catch (Exception e) {
            producer.abortTransaction();
        } finally {
            producer.close();
        }
    }
}